package util;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.protocol.Protocol;
import weibo4j.model.MySSLSocketFactory;
import weibo4j.org.json.*;

public class Auth4Code {
	public static String getAccessToken(){
		Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
		Protocol.registerProtocol("https", myhttps);
		String result= null;
		HttpClient client = new HttpClient();
		PostMethod postMethod = new PostMethod(
		"https://api.t.sina.com.cn/oauth2/authorize");
		postMethod.addParameter("client_id", "234953712"); //appkey
		postMethod.addParameter(
				"redirect_uri",
		"http://a8ad.z9.ipc.la/index.php/website/callback");      //oauth2 回调地址   
		postMethod.addParameter("response_type", "code");
		postMethod.addParameter("action", "submit");
		postMethod.addParameter("userId", "yuxinphp@gmail.com");    //微博帐号
		postMethod.addParameter("passwd", "smallstar101101");    //帐号密码
		try {
			client.executeMethod(postMethod);
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String url=postMethod.getResponseHeader("location").getValue();
		String params=url.substring(url.lastIndexOf("?")+1);
		Map<String ,String> paramsMap= new HashMap<String, String>();
		for(String s:params.split("&")){
			String[] t=s.split("=");
			paramsMap.put(t[0],t[1]);
		}
		String code=paramsMap.get("code");
		PostMethod tokenMethod=new PostMethod("https://api.t.sina.com.cn/oauth2/access_token");
		tokenMethod.addParameter("client_id", "234953712");       //appkey
		tokenMethod.addParameter("client_secret", "a5d8fa48c8a7ffa167a5444a4e5139b9");   //appsecret
		tokenMethod.addParameter("grant_type","authorization_code");
		tokenMethod.addParameter("code",code);           //上一步骤拿到的code
		tokenMethod.addParameter("redirect_uri","http://a8ad.z9.ipc.la/index.php/website/callback");   //回调地址
		try {
			client.executeMethod(tokenMethod);
			try {
				JSONObject key = new JSONObject(tokenMethod.getResponseBodyAsString());
				return (String) key.get("access_token");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	
			System.out.println(result);
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;

	}
}

